package cn.rick.controller;

import cn.dev33.satoken.util.SaResult;
import cn.rick.entity.SysDept;
import cn.rick.entity.SysUser;
import cn.rick.service.ISysDeptService;
import cn.rick.service.ISysUserService;
import cn.rick.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Rick
 * @date 2022-10-21 08:44
 */
@RestController
@RequestMapping("/api/dept")
@Api(value = "部门控制", tags = {"部门控制"})
public class DeptController {

    @Resource
    ISysDeptService iSysDeptService;

    @Resource
    ISysUserService iSysUserService;

    /**
     * 通过参数获取所有部门信息
     *
     * @param sysDept
     * @return
     */
    @GetMapping("/getData")
    @ApiOperation("通过参数获取所有部门信息")
    public SaResult getData(SysDept sysDept) {
        List<SysDept> list = iSysDeptService.selectAllByParam(sysDept);
        if (StringUtils.isNotEmpty(sysDept.getDeptName()) || "1".equals(sysDept.getStatus())) {
            return SaResult.data(list);
        } else {
            return SaResult.data(category0(list));
        }
    }

    /**
     * 保存部门信息
     *
     * @param sysDept
     * @return
     */
    @PostMapping("/save")
    @ApiOperation("保存部门信息")
    public SaResult save(@RequestBody SysDept sysDept) {
        if (Objects.nonNull(sysDept)) {
            LambdaQueryWrapper<SysDept> query = new LambdaQueryWrapper<>();
            query.eq(SysDept::getDeptName, sysDept.getDeptName());
            if (Objects.nonNull(iSysDeptService.getOne(query))) {
                return SaResult.error("部门名称已存在，请更换");
            }

            if (sysDept.getDeptId() != null) {
                LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SysDept::getDeptId, sysDept.getDeptId());
                if (!sysDept.getStatus().equals(iSysDeptService.getOne(queryWrapper).getStatus())) {
                    SysDept update = new SysDept();
                    update.setStatus(sysDept.getStatus());

                    if (sysDept.getParentId().equals(0L)) {
                        iSysDeptService.update(update, null);
                    } else {
                        LambdaQueryWrapper<SysDept> queryWrapper1 = new LambdaQueryWrapper<>();
                        queryWrapper1.eq(SysDept::getParentId, sysDept.getDeptId());
                        iSysDeptService.update(update, queryWrapper1);
                    }
                }

                boolean save = iSysDeptService.updateById(sysDept);
                if (save) {
                    return SaResult.ok("修改成功");
                } else {
                    return SaResult.error("修改失败，请稍后再试");
                }
            } else {
                SysDept byId = iSysDeptService.getById(sysDept.getParentId());
                StringBuilder sb = new StringBuilder(byId.getAncestors());
                String ancestors = String.valueOf(sb.append(",").append(byId.getDeptId()));
                sysDept.setAncestors(ancestors);
                boolean save = iSysDeptService.save(sysDept);
                if (save) {
                    return SaResult.ok("新增成功");
                } else {
                    return SaResult.error("修改失败，请稍后再试");
                }
            }
        } else {
            return SaResult.error("参数错误！请稍后再试");
        }
    }

    /**
     * 删除部门
     *
     * @param deptId
     * @return
     */
    @DeleteMapping("/del")
    @ApiOperation("删除部门")
    public SaResult del(Long deptId) {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDept::getParentId, deptId);
        List<SysDept> list = iSysDeptService.list(queryWrapper);
        if (list.size() > 0) {
            return SaResult.error("该部门下还有<" + list.size() + ">条子部门，无法删除！");
        } else {
            LambdaQueryWrapper<SysUser> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysUser::getDeptId, deptId);
            List<SysUser> list1 = iSysUserService.list(queryWrapper1);
            if (list1.size() > 0) {
                return SaResult.error("该部门下还有<" + list1.size() + ">个员工，无法删除！");
            } else {
                if (iSysDeptService.removeById(deptId)) {
                    return SaResult.ok("删除成功");
                } else {
                    return SaResult.error("删除失败，请稍后再试");
                }
            }
        }
    }


    public List<SysDept> category0(List<SysDept> param) {
        List<SysDept> category0 = param.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());
        category0.stream().forEach(category0Item -> {
            List<SysDept> category1 = param.stream().filter(item -> item.getParentId().equals(category0Item.getDeptId())).collect(Collectors.toList());
            category1.stream().forEach(category1Item -> {
                List<SysDept> category2 = param.stream().filter(item -> item.getParentId().equals(category1Item.getDeptId())).collect(Collectors.toList());
                category2.stream().forEach(category2Item -> {
                    List<SysDept> category3 = param.stream().filter(item -> item.getParentId().equals(category2Item.getDeptId())).collect(Collectors.toList());
                    category3.stream().forEach(category3Item -> {
                        List<SysDept> category4 = param.stream().filter(item -> item.getParentId().equals(category3Item.getDeptId())).collect(Collectors.toList());
                        category3Item.setChildren(category4);
                    });
                    category2Item.setChildren(category3);
                });
                category1Item.setChildren(category2);
            });
            category0Item.setChildren(category1);
        });
        return category0;
    }

}
